package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;

/**
 * 微信服务实现类
 * @author liuli
 * @date 2025-08-20
 */
@Slf4j
@Service
public class WechatServiceImpl implements WechatService {

    // 小程序登录url
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";
    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";



    //小程序appid
    @Value("${wechat.appid}")
    private String appid;
    //小程序密钥
    @Value("${wechat.secret}")
    private String secret;

    /**
     * 根据微信code获取open
     * @param code 代码
     * @return openid
     */
    @Override
    public String getOpenid(String code) {
        try {
            //拼接请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("appid", appid);
            params.put("secret", secret);
            params.put("js_code", code);
            //发起请求
            String result = HttpUtil.get(REQUEST_URL, params);
            //解析结果
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (ObjectUtil.isNotEmpty(jsonObject.getString("errcode"))) {
                throw new BaseException("获取openid失败,失败码为:"+jsonObject.getIntValue("errcode"));
            }
            //返回openid
            log.info("成功获取openid: {}",jsonObject.getString("openid"));
            return jsonObject.getString("openid");
        } catch (Exception e) {
            log.error("获取openid失败: {}",e.getMessage());
            throw new BaseException("获取openid失败"+e.getMessage());
        }
    }

    @Override
    public String getPhone(String code) {
        //拼接请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("code", code);
        //发起请求
        String result = HttpUtil.post(PHONE_REQUEST_URL+ getAccessToken(), JSONUtil.toJsonStr(params));
        //解析结果
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getInteger("errcode")!= 0) {
            throw new BaseException("获取手机号失败"+jsonObject);
        }
        //返回手机号
        log.info("成功获取手机号: {}",jsonObject.getJSONObject("phone_info"));
        return JSONObject.parseObject(jsonObject.getString("phone_info")).getString("phoneNumber");
    }

    @Override
    public String getAccessToken() {
        try {
            //拼接请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("appid", appid);
            params.put("secret", secret);
            //发起请求
            String result = HttpUtil.get(TOKEN_URL, params);
            //解析结果
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (StringUtils.isBlank(jsonObject.getString("access_token"))) {
                throw new BaseException("获取access_token失败,失败码为:"+jsonObject.getIntValue("errcode"));
            }
            //返回access_token
            log.info("成功获取access_token: {}",jsonObject.getString("access_token"));
            return jsonObject.getString("access_token");
        } catch (Exception e) {
            log.error("获取access_token失败: {}",e.getMessage());
            throw new BaseException("获取access_token失败"+e.getMessage());
        }
    }


}